package com.guqj.thread.concurrent.lock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLockTest extends Thread {

	private volatile boolean fire = false;
	private Lock lock = new ReentrantLock();
	private Condition condition = lock.newCondition();

	@Override
	public void run() {
		lock.lock(); // lock()/unlock()：就是普通的获取锁和释放锁方法，lock()会阻塞直到成功
		try {
			try {
				while (!fire) {
					condition.await();
				}
			} finally {
				lock.unlock();
			}
			System.out.println("thread fired...");
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	public void fire() {
		lock.lock();
		try {
			this.fire = true;
			condition.signal();
		} finally {
			lock.unlock();
		}
	}

	public static void main(String[] args) throws InterruptedException {
		ReentrantLockTest test = new ReentrantLockTest();
		test.start();
		Thread.sleep(2000);
		test.fire();
	}
}
